package com.example.sfzreader.core;

import android.content.Context;
import android.os.Environment;
import android.os.Looper;
import android.text.TextUtils;
import android.widget.Toast;


import com.example.sfzreader.bean.IDCardBean;
import com.example.sfzreader.bean.ReaderResultBean;
import com.example.sfzreader.contact.Contacts;
import com.ivsign.android.IDCReader.IDCReaderSDK;
import com.example.mt3yreader.NativeFunc;
import com.example.sfzreader.utils.GsonUtils;
import com.example.sfzreader.utils.ToolFun;
import com.example.sfzreader.utils.UsbDevPermission;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;

/**
 * 身份证读取client
 */
public class IDCardReaderClient {


    private boolean isReadFinger;
    private IReaderResult iReaderResult;
    private Context context;

    private UsbDevPermission usbPermission;


    public IDCardReaderClient(Context context, boolean isReadFinger, int deviceType, IReaderResult iReaderResult) {
        this.context = context;
        this.isReadFinger = isReadFinger;
        this.iReaderResult = iReaderResult;
    }

    public static IDCardReaderClientHelper build() {
        return new IDCardReaderClientHelper();
    }


    private void backResult(ReaderResultBean readerResultBean, String msg, int code) {
        readerResultBean.setMessage(msg);
        readerResultBean.setCode(code);
        if (iReaderResult != null) {
            iReaderResult.onRes(GsonUtils.toJson(readerResultBean));
        }
    }

    /**
     * 读取身份证中所有的信息
     */
    public void readIDCard() {
        if (!isDeviceAvaliable()){
            IDCardReaderManager.getInstance().init(tip -> { });
        }
        ReaderResultBean readerResultBean = new ReaderResultBean();
        final int[] idcMsgLen = new int[2];
        final byte[] idcMsg = new byte[4096];
        String strBmpFilePath;
        //开始时间
        long startTime = System.currentTimeMillis();
        long mendTime = 0;
        //读取指纹
        int readFinger = isReadFinger ? Contacts.READ_FINGER : Contacts.READ_NO_FINGER;
        int res = NativeFunc.mt8IDCardReadAll(idcMsgLen, idcMsg, readFinger);
        //res 0 读取成功
        //读取身份证中照片信息
        byte[] photoDatas = null;
        if (res == 0) {
//            mendTime = System.currentTimeMillis();

            try {
                photoDatas = AnysizeIDCMsg.CombinationWltDataWithNewVersion(idcMsgLen, idcMsg, readFinger);
            } catch (Exception e) {
                e.printStackTrace();
                backResult(readerResultBean, "[读取身份证头像信息失败]" + e.getMessage(), res);
            }
            //read idc so库可用状态
            if (IDCReaderSDK.GetLoadSoState()) {
                ToolFun.initLicData(context, IDCReaderSDK.GetLicensePath());
                final int resT = IDCReaderSDK.Init();

                if (resT == 0) {
                    int t = IDCReaderSDK.unpack(photoDatas, AnysizeIDCMsg.byLicData);
                    if (t == 1) {
                        strBmpFilePath = Environment.getExternalStorageDirectory() + "/wltlib/zp.bmp";
                        FileInputStream fis = null;
                        try {
                            fis = new FileInputStream(strBmpFilePath);

                        } catch (FileNotFoundException e) {
                            e.printStackTrace();
                            backResult(readerResultBean, "[写入身份证头像信息失败]" + e.getMessage(), res);
                        } finally {
                            try {
                                assert fis != null;
                                fis.close();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }

                    } else {
                        backResult(readerResultBean, "身份证照片解码库解码失败", t);
                    }
                } else {
                    backResult(readerResultBean, "身份证照片解码库初始化失败,请检查< " + Environment.getExternalStorageDirectory() + "/wltlib/ > 目录下是否有照片解码库授权文件!", res);
                }
            } else {
                backResult(readerResultBean, "未找到身份证照片解码库libwltdecode.so!", res);
            }


            HashMap<String, byte[]> fIDCMsg = AnysizeIDCMsg.anysizeIDCMsg(readFinger, idcMsgLen[0], idcMsg);
            String idType = "";

            try {
                idType = new String(fIDCMsg.get("TypeID"), "UTF-16LE");
                //compareTo比较两个字符串ASCII码的整形，【整形】返回两个ASCII码整形差值，如果返回0说明两个相等
                //如果小于0，说明前面的字符串小于后面的字符串
                //如果大于0，说明前面的字符串大于后面的字符串
                IDCardBean idCardBean = new IDCardBean();
                idCardBean.setDateStart(getIDItemStr(fIDCMsg.get("DateStart")));
                idCardBean.setDateEnd(getIDItemStr(fIDCMsg.get("DateEnd")));
                if (Contacts.OTHER_PEOPLE.compareTo(idType) == 0) {
                    idCardBean.setEnglishName(getIDItemStr(fIDCMsg.get("ForeignName")));
                    idCardBean.setSex(getIDItemStr(fIDCMsg.get("Sex")));
                    idCardBean.setForeverLiveCode(getIDItemStr(fIDCMsg.get("IDNum")));
                    idCardBean.setCountryCode(getIDItemStr(fIDCMsg.get("CountryCode")));
                    idCardBean.setChineseName(getIDItemStr(fIDCMsg.get("ChinaName")));
                    idCardBean.setBirthDate(getIDItemStr(fIDCMsg.get("Birth")));
                    idCardBean.setIdVersionCode(getIDItemStr(fIDCMsg.get("IDVer")));
                    idCardBean.setCurrentGovCode(getIDItemStr(fIDCMsg.get("Issued")));
                    idCardBean.setIdTypeFlag(getIDItemStr(fIDCMsg.get("TypeID")));
                    idCardBean.setReserveInfo(getIDItemStr(fIDCMsg.get("Reserved")));
                } else {
                    idCardBean.setChineseName(getIDItemStr(fIDCMsg.get("ChinaName")));
                    idCardBean.setSex(getIDItemStr(fIDCMsg.get("Sex")));
                    if (Contacts.CHINESE_PEOPLE.compareTo(idType) != 0) {
                        idCardBean.setNationCh(getIDItemStr(fIDCMsg.get("Nation")));
                    } else {
                        idCardBean.setPassNumCh(getIDItemStr(fIDCMsg.get("PassNumber")));
                        idCardBean.setIssueTimes(getIDItemStr(fIDCMsg.get("IssueTime")));
                        idCardBean.setIdTypeFlag(getIDItemStr(fIDCMsg.get("TypeID")));
                    }
                    idCardBean.setBirthDate(getIDItemStr(fIDCMsg.get("Birth")));
                    idCardBean.setAddressCh(getIDItemStr(fIDCMsg.get("Address")));
                    idCardBean.setPassNumCh(getIDItemStr(fIDCMsg.get("IDNum")));
                    idCardBean.setVisaAuthority(getIDItemStr(fIDCMsg.get("Issued")));
                }
                readerResultBean.setData(idCardBean);
            } catch (UnsupportedEncodingException e) {
                backResult(readerResultBean, "[读取身份信息字段解码失败]" + e.getMessage() + getDeviceStatus(), res);
                if (getDeviceStatus() != 0) {
                    IDCardReaderManager.getInstance().closeConnect();
                    initReadIdCard();
                }
                return;
            }

        } else {
            backResult(readerResultBean, "[获取身份证信息失败]" + getDeviceStatus(), res);
            if (getDeviceStatus() != 0) {
                IDCardReaderManager.getInstance().closeConnect();
                initReadIdCard();
            }
            return;
        }
        String readerRes = GsonUtils.toJson(readerResultBean);
        if (!TextUtils.isEmpty(readerRes) && iReaderResult != null) {
            iReaderResult.onRes(readerRes);
        }
    }

    private void initReadIdCard() {
        IDCardReaderManager.getInstance().setDeviceType(Contacts.USB_MODE).init(tip -> {
            Looper.prepare();
            Toast.makeText(context, tip, Toast.LENGTH_SHORT).show();
            Looper.loop();
        });
    }

    private int getDeviceStatus() {
        byte Status[] = new byte[5];
        int status = NativeFunc.mt8GetDeviceStatus(Status);
        if (status != 0) {
            return status;
        } else {
            return Status[0];
        }
    }


    /**
     * 获取读卡器的状态
     * @return true正常 false不正常
     */
    private boolean isDeviceAvaliable(){
        return getDeviceStatus()==0;
    }

    /**
     * 单纯读取身份证号码
     */
    public void readIDCardNum() {
        int res = 0;
        byte rlen[] = new byte[5];
        byte idNum[] = new byte[64];
        ReaderResultBean readerResultBean = new ReaderResultBean();
        res = NativeFunc.mt8IDCardReadIDNUM(rlen, idNum);
        if (res == 0) {
            byte[] asc = new byte[rlen[0] * 2];
            NativeFunc.mt8hexasc(idNum, asc, rlen[0]);
            String showIDNum = new String(asc);
            readerResultBean.setIdCardNum(showIDNum);
            readerResultBean.setCode(200);
        } else {
            readerResultBean.setCode(res);
            readerResultBean.setMessage("读身份证卡号失败");
        }
        String readerRes = GsonUtils.toJson(readerResultBean);
        if (iReaderResult != null) {
            iReaderResult.onRes(readerRes);
        }
    }


    public int getCardStatus() {
        byte[] params = new byte[5];
        int i = NativeFunc.mt8GetDeviceStatus(params);
        return i;
    }

    private String getIDItemStr(byte[] itemByte) {
        try {
            return new String(itemByte, "UTF-16LE");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return "";
    }
}
